from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from django.views.generic import View
from .forms import MessageBoardForm
from django.forms.utils import ErrorDict


class IndexView(View):
    def get(self, request, *args, **kwargs):
        form = MessageBoardForm()
        return render(request, 'index.html', context={'form': form})

    def post(self, request, *args, **kwargs):
        form = MessageBoardForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            email = form.cleaned_data.get('email')
            reply = form.cleaned_data.get('reply')
            print('title：', title)
            print('content：', content)
            print('email：', email)
            print('reply：', reply)
            return HttpResponse('success')
        else:
            # print(type(form.errors))    # TODO: <class 'django.forms.utils.ErrorDict'>
            print(form.errors.get_json_data())
            print(type(form.errors.get_json_data()))
            # return JsonResponse(form.errors.as_data())
            return HttpResponse(form.errors.get_json_data())
